package com.lb.shopguide.ui.fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.GuideAdBean;
import com.lb.shopguide.entity.UpdateInfoBean;
import com.lb.shopguide.ui.activity.GuideActivity;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Create by kangzhao on 2018/12/4
 */
public class FragmentAd extends BaseCommonFragment {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_time)
    TextView tvTime;

    private UpdateInfoBean updateInfoBean;
    private GuideAdBean guideAdBean;

    private MyCountDown countDown;

    public static FragmentAd newInstance(UpdateInfoBean updateInfoBean, GuideAdBean guideAdBean) {
        FragmentAd fragment = new FragmentAd();
        Bundle bundle = new Bundle();
        if (updateInfoBean != null) {
            bundle.putSerializable(AppConstant.UPDATE_BEAN, updateInfoBean);
        }
        bundle.putSerializable(AppConstant.GUIDANCE_BEAN, guideAdBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_ad;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.UPDATE_BEAN)) {
            updateInfoBean = (UpdateInfoBean) bundle.getSerializable(AppConstant.UPDATE_BEAN);
        } else {
            updateInfoBean = null;
        }
        if (bundle.containsKey(AppConstant.GUIDANCE_BEAN)) {
            guideAdBean = (GuideAdBean) bundle.getSerializable(AppConstant.GUIDANCE_BEAN);
        }
    }

    @Override
    public void initView() {
        ImageLoaderUtils.display(mContext, ivBack, guideAdBean.getLoadingPicUrl1());
        countDown();
//        showTestNotification(mContext);
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    @OnClick(R.id.iv_back)
    void onBackClick() {
        jump(true);
        releaseCount();
    }


    @Override
    public String getPageTag() {
        return FragmentAd.class.getCanonicalName();
    }

    @Override
    public void onPause() {
        super.onPause();
//        releaseCount();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        releaseCount();
    }

    @OnClick(R.id.tv_time)
    public void onTimeClick() {
        jump(false);
    }

    private void countDown() {
        if (countDown == null) {
            countDown = new MyCountDown(5000, 1000);
        }
        countDown.start();
    }

    private void releaseCount() {
        if (countDown != null) {
            countDown.cancel();
            countDown = null;
        }
    }


    class MyCountDown extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("跳过" + (millisUntilFinished / 1000 + 1) + "s");
        }

        @Override
        public void onFinish() {
            if (tvTime != null) {
                tvTime.setText("跳过0s");
            }
            jump(false);
        }
    }
    private void showTestNotification(Context context) {
        prepareNotification(context);
    }

    private void prepareNotification(Context context) {
        int notificationId = 100;
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, AppConstant.CHANNEL_BOSS_NOTIFICATION);
        Intent targetIntent = new Intent(context, GuideMainActivity.class);
        Bundle targetBundle = new Bundle();
        targetBundle.putInt(AppConstant.NOTIFICATION_TARGET, AppConstant.NOTIFICATION_TARGET_REC);
        targetBundle.putString(AppConstant.NOTIFICATION_INFO, "{jumpMode:1,pageSdCode:\"TSSY\"}");
        targetIntent.putExtras(targetBundle);
        mBuilder.setContentTitle("测试")//设置通知栏标题
                .setContentText("测试内容") //设置通知栏显示内容
                .setContentIntent(PendingIntent.getActivity(context, 1, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT)) //设置通知栏点击意图
//  .setNumber(number) //设置通知集合的数量
                .setTicker(JPushInterface.EXTRA_NOTIFICATION_TITLE + "消息")//通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
//.setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSound(Uri.parse("android.resource://" + GuideApplication.getAppContext().getPackageName() + "/" + R.raw.beep))
                .setSmallIcon(R.drawable.logo);//注：PendingIntent开启新的界面，intent携带值传递的时候，PendingIntent的类型是FLAG_UPDATE_CURRENT，新的值过来，自动更新，intent需要设置Action才可以获得传递的值
        adapterAndroidOreo(mNotificationManager);
        mNotificationManager.notify(notificationId, mBuilder.build());
    }

    /**
     * 适配android8.0
     *
     * @param mNotificationManager
     */
    private void adapterAndroidOreo(NotificationManager mNotificationManager) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(AppConstant.CHANNEL_BOSS_NOTIFICATION, "身边店", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableVibration(true);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .build();
            channel.setSound(Uri.parse("android.resource://" + GuideApplication.getAppContext().getPackageName() + "/" + R.raw.beep), audioAttributes);
            mNotificationManager.createNotificationChannel(channel);
        }
    }

    private void jump(boolean flag) {
        if (!TextUtils.isEmpty(mUserConfigManager.getUserId())) {
            Intent intent = null;
            if (mUserConfigManager.getTerminalType() == AppConstant.TERMINAL_TYPE_GUIDE) {
                intent = ((GuideActivity) _mActivity).getGuideMainActivityIntent();
            } else if (mUserConfigManager.getTerminalType() == AppConstant.TERMINAL_TYPE_BOSS) {
                intent = ((GuideActivity) _mActivity).getBossMainActivityIntent();
            } else if (mUserConfigManager.getTerminalType() == -1) {//之前的导购端，不存在这个字段，直接进入导购端
                mUserConfigManager.setTerminalType(AppConstant.TERMINAL_TYPE_GUIDE);
                intent = ((GuideActivity) _mActivity).getGuideMainActivityIntent();
            }
            if (updateInfoBean != null && intent != null) {
                intent.putExtra(AppConstant.UPDATE_BEAN, updateInfoBean);
            }
            if (flag) {
                if (guideAdBean != null) {
                    guideAdBean.setJumpUrl(BizUtil.fixActivityUrl(guideAdBean.getJumpUrl(),"XD0011"));
                    intent.putExtra(AppConstant.GUIDEAD_BEAN, guideAdBean);
                }
            }
            startActivity(intent);
            _mActivity.finish();
        } else {
//            startWithPop(FragmentEnterPhone.newInstance(updateInfoBean));// FragmentManager is already executing transactions
            startWithPop(FragmentChooseRole.newInstance(updateInfoBean));
        }
    }
}
